﻿using Sidvall.AuthorizationManager.Data;
using Sidvall.DataPortal;
using Sidvall.Serialization;

namespace Sidvall.AuthorizationManager.Business
{
    public class ServerConnectionProvider : IServerConnectionProvider
    {
        #region Public Members

        #region GetServerConnection

        public ServerConnection GetServerConnection(Sidvall.DataPortal.DataPortalStrategy dataPortalStrategy, Sidvall.Business.IDataPortalContext dataPortalContext, string context)
        {
            Sidvall.AuthorizationManager.Net.Services.V1.ServerConnection serverConnection;

            if (dataPortalStrategy?.MasterServerConnection != null)
                return dataPortalStrategy.MasterServerConnection;

            switch (Sidvall.AuthorizationManager.Configuration.SettingsManager.ProcessType.ToEnum(ProcessType.Server))
            {
                case ProcessType.Client:
                    if (dataPortalContext != null)
                        serverConnection = ParameterManager.GetServerConnection(dataPortalContext.Parameters);
                    else
                        serverConnection = ParameterManager.GetServerConnection(context.ToNullableInt32());
                    if (serverConnection == null)
                        throw new System.ArgumentException("Invalid Server");
                    return Sidvall.AuthorizationManager.SystemContext.Current.GetServerConnection(serverConnection);
                default:
                    if (dataPortalContext != null)
                        serverConnection = ParameterManager.GetServerConnection(dataPortalContext.Parameters);
                    else
                        serverConnection = ParameterManager.GetServerConnection(context.ToNullableInt32());
                    return Sidvall.AuthorizationManager.SystemContext.Current.GetServerConnection(serverConnection);
            }
        }

        #endregion

        #endregion
    }
}
